package com.chenqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenqi.dao.RelationshipMapper;
import com.chenqi.dao.UserMapper;
import com.chenqi.model.entity.Relationship;
import com.chenqi.model.entity.User;
import com.chenqi.service.RelationshipService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description:
 * @program: ardaicommunity
 * @author: ChenQi
 * @create: 2021-03-2021/3/13-09-07
 */
@Slf4j
@Service
@Transactional(rollbackFor = {Exception.class})
public class RelationshipServiceImpl implements RelationshipService {

    @Autowired
    private RelationshipMapper relationshipMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int subscribe(Integer parent_id, Integer follower_id) {
        try{
            Relationship relationship = new Relationship();
            relationship.setParentId(parent_id).setFollowerId(follower_id);
            int i = relationshipMapper.insert(relationship);
            //同时增加1被关注用户的关注数
            User user = userMapper.selectById(parent_id);
            user.setFollowerCount(user.getFollowerCount() + 1);
            userMapper.updateById(user);
            return i;
        }catch (Exception e) {
            log.error("Exception:{}",e.getMessage());
            return 0;
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int unsubscribe(Integer parent_id, Integer follower_id) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("parent_id", parent_id);
            queryWrapper.eq("follower_id", follower_id);
            int i = relationshipMapper.delete(queryWrapper);
            //同时减少1被关注用户的关注数
            User user = userMapper.selectById(parent_id);
            user.setFollowerCount(user.getFollowerCount() - 1);
            userMapper.updateById(user);
            return i;
        }catch (Exception e){
            log.error("Exception:{}",e.getMessage());
            return 0;
        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Relationship validate(Integer parent_id, Integer follower_id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", parent_id);
        queryWrapper.eq("follower_id", follower_id);
        Relationship relationship = relationshipMapper.selectOne(queryWrapper);
        return relationship;
    }
}
